var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');

var bodyParser = require("body-parser");

//返回通用消息模板
var cMsg = require("./common/ResultMessage");


{// jwt 引用拓展
  var expressJwt = require("express-jwt");
  var jwt = require("jsonwebtoken");
}

{//路由配置 start
  var indexRouter = require('./routes/index');
  var usersRouter = require('./routes/users');
  var testRouter = require('./routes/api/test');
}

var app = express();

// post请求中间件
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));
// jwt中间件
app.use(expressJwt({
  secret: "secret"//加密密钥，可换
}).unless({
  path: ["/users/login"]//添加不需要token的接口
}));
// 未携带token请求接口会出错，触发这个
app.use(function(err, req, res, next) {
  if (err.name === "UnauthorizedError") {
      res.status(401).send(new cMsg(err,401));
  }
});



// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

app.use(logger('dev'));

// app.use(express.json());
// app.use(express.urlencoded({ extended: false }));


app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/test', testRouter);



// catch 404 and forward to error handler
app.use(function (req, res, next) {
  next(createError(404));
});

// error handler
app.use(function (err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
